package com.turing.common.util;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

public class ImageUtil {

    // 日志相关
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    public static BufferedImage generateThumbnail(File uploadFile, List<CoordinateUtil.Coordinate> coordinates) {
        long l1 = System.currentTimeMillis();
        BufferedImage background = null;

        try {
            background = ImageIO.read(new File(uploadFile.getPath()));
            if (!CollectionUtils.isEmpty(coordinates)) {
                int size = coordinates.size();
                for (int i = 0; i <= size - 1; i++) {

                    Graphics2D bgG2 = (Graphics2D) background.getGraphics();

                    CoordinateUtil.Coordinate coordinate1 = coordinates.get(i);
                    //遮罩层大小
                    int coverWidth = coordinate1.getWidth();
                    int coverHeight = coordinate1.getHeight();
                    //遮罩层位置
                    int coverX = coordinate1.getOrdinate();
                    int coverY = coordinate1.getHorizontal();

                    //创建黑色遮罩层
                    BufferedImage cover = new BufferedImage(coverWidth, coverHeight, BufferedImage.TYPE_INT_RGB);
                    Graphics2D coverG2 = (Graphics2D) cover.getGraphics();
                    coverG2.setColor(new Color(42, 255, 9));
                    coverG2.fillRect(0, 0, coverWidth, coverHeight);
                    coverG2.dispose();

                    //开启透明度
                    bgG2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
                    //描绘
                    bgG2.drawImage(cover, coverX, coverY, coverWidth, coverHeight, null);
                    //结束透明度
                    bgG2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
                    bgG2.dispose();

                }
                long l2 = System.currentTimeMillis();
                logger.info("高亮图片耗时: " + (l2 - l1) + " 毫秒");
                return background;
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
            return background;
        }
        return background;
    }

    /**
     * 获取输入文件流的扩展名
     *
     * @param
     * @throws IOException
     */
    private static String getFileExtension(File uploadFile) {
        String fileName = uploadFile.getName();
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 复制图片
     *
     * @param source
     * @param nameTmp
     * @throws IOException
     */
    public static void copyImage(String source, String nameTmp) throws IOException {

        //1.创建字节缓冲输入流对象，构造方法中传递字节输入流
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source));

        //2.创建字节缓冲输出流对象，构造方法中传递字节输出流
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(nameTmp));

        //3.使用字节缓冲输出流对象中的方法read，读取文件
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = bis.read(bytes)) != -1) {
            bos.write(bytes, 0, len);
        }
        bos.close();
        bis.close();
    }

    /**
     * 计算图片像素大小
     *
     * @param uploadFile
     * @return
     */
    private static List<Integer> getImageSize(File uploadFile) {
        List<Integer> integerList = new ArrayList<>();

        FileChannel fc = null;
        if (uploadFile.exists() && uploadFile.isFile()) {
            try {
                FileInputStream fs = new FileInputStream(uploadFile);
                fc = fs.getChannel();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        BufferedImage bi = null;
        try {
            bi = ImageIO.read(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        int width = bi.getWidth();
        int height = bi.getHeight();

        logger.info("原始图片 宽：像素-----" + width + "高：像素" + height);
        integerList.add(width);
        integerList.add(height);
        return integerList;
    }

    public static void compressPic(String srcFilePath, String descFilePath, Float quality) throws IOException {
        File input = new File(srcFilePath);
        BufferedImage image = ImageIO.read(input);

        // 指定写图片的方式为 jpg
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();

        // 先指定Output，才能调用writer.write方法
        File output = new File(descFilePath);
        OutputStream out = new FileOutputStream(output);
        ImageOutputStream ios = ImageIO.createImageOutputStream(out);
        writer.setOutput(ios);

        ImageWriteParam param = writer.getDefaultWriteParam();
        if (param.canWriteCompressed()) {
            // 指定压缩方式为MODE_EXPLICIT
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            // 压缩程度，参数qality是取值0~1范围内
            param.setCompressionQuality(quality);
        }
        // 调用write方法，向输入流写图片
        writer.write(null, new IIOImage(image, null, null), param);

        out.close();
        ios.close();
        writer.dispose();
    }

    /**
     * 待合并的两张图必须满足这样的前提，如果水平方向合并，则高度必须相等；如果是垂直方向合并，宽度必须相等。 mergeImage方法不做判断，自己判断。
     *
     * @return 返回合并后的BufferedImage对象
     * @throws IOException
     */
    public static BufferedImage mergeImage(List<BufferedImage> bil) {

        // 生成新图片
        BufferedImage DestImage;

        //计算图片总大小
        int h0 = 0;
        int w0 = 0;
        for (BufferedImage bufferedImage : bil) {
            h0 += bufferedImage.getHeight();
            w0 = bufferedImage.getWidth();
            System.out.println(bufferedImage.getWidth() + "/n");
        }
        DestImage = new BufferedImage(w0, h0, BufferedImage.TYPE_INT_RGB);

        //合并图片
        int startY = 0;
        for (BufferedImage img : bil) {
            int w = img.getWidth();
            int h = img.getHeight();
            int[] imageArray = new int[w * h];
            imageArray = img.getRGB(0, 0, w, h, imageArray, 0, w);
            DestImage.setRGB(0, startY, w, h, imageArray, 0, w);
            startY += h;
        }

        return DestImage;
    }
}